package dao;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.swing.ListModel;

import systemServer.members.Member;
import systemServer.reproduction.Play;

public class MemberDAO {
	private static MemberDAO instance = new MemberDAO();
	
	private HashMap<String, Member> members;
	
	private MemberDAO() {
		members = new HashMap<String, Member>();
	}

	public static MemberDAO getInstance() {
		return instance;
	}

	public void addMember(Member m) {
		System.out.println("Preparado para meter un usuario");
		Transaction tx = Temp.pm.currentTransaction();
		try {
			tx.begin();
			Temp.pm.makePersistent(m);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
		}
		System.out.println("Usuario introducido");
	}
	private void loadMembers() {
		members.clear();
		Transaction tx=Temp.pm.currentTransaction();
	     try{
	    	 tx.begin();
	    	 Query query = Temp.pm.newQuery(Member.class);
	    	 List<Member> listMembers= (List<Member>) query.execute();
	    	 tx.commit();
	    	 for (Member member : listMembers)
	    		 members.put(member.getUsername(), member);
	     }catch (Exception e){
	    	 e.printStackTrace();
	     }finally{
	    	 if (tx.isActive())
	            {
	                tx.rollback();
	            }
	     }
	}
	public Member getMember(String userName) {
//		 Transaction tx=Temp.pm.currentTransaction();
//	     Member member = null;
//	     try{
//	    	 tx.begin();
//	    	 Query query = Temp.pm.newQuery(Member.class);
//	    	 query.setFilter("username == \'"+ userName+"\'");
//	    	 List<Member> listMember= (List<Member>) query.execute();
//	    	 
//	    	 member = listMember.get(0);
//	    	 tx.commit();
//	     }catch (Exception e){
//	    	 e.printStackTrace();
//	     }finally{
//	    	 if (tx.isActive())
//	            {
//	                tx.rollback();
//	            }
//	     }
		if (members.isEmpty())
			loadMembers();
	     return members.get(userName);
	}
	
//	public List<Play> getMemberPlays(Member m) {
//		Transaction tx=Temp.pm.currentTransaction();
//	    List<Play> listPlays = null; 
//		try{
//	    	 tx.begin();
//	    	 Query query = Temp.pm.newQuery(Play.class);
//	    	 query.setFilter("member == \'"+ m.getUsername()+"\'");
//	    	 listPlays= (List<Play>) query.execute();
//	    	 tx.commit();
//	     }catch (Exception e){
//	    	 e.printStackTrace();
//	     }finally{
//	    	 if (tx.isActive())
//	            {
//	                tx.rollback();
//	            }
//	     }
//	     return listPlays;
//	}
}
